python 发邮件

   

python发送邮件并带有附件,如果安装相关的包,先用pip安装这些包:smtplib,email

import
smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.application import MIMEApplication


# msg,邮件的正文
def send_mail(msg):
   
# 设置邮件服务器,请按实际情况修改
   
mail_host = "smtp.xxx.com.cn"
   
# 登录邮件的帐号,请按实际情况修改
   
mail_user = "test"
   
# 登录邮件的密码,请按实际情况修改
   
mail_pass = "test123456"
   
# 发送人,请按实际情况修改
   
sender = 'test@xxx.com.cn'
   
# 接收人,,请按实际情况修改,多个接收人以逗号隔开
   
receivers = ['test1@xxx.com.cn', 'test2@xxx.com.cn']
   
# msg = MIMEMultipart('mixed')
   
msg = MIMEMultipart('related')
   
# 邮件标题,请按实际修改
   
msg['Subject'] = u"这里是邮件的标题 "
   
msg['From'] = sender
   
# 收件人为多个收件人,通过join将列表转换为以;为间隔的字符串
   
msg['To'] = ";".join(receivers)

   
# 设置邮件正文
   
html_msg = msg
    text_plain = MIMEText(html_msg,
'html', 'utf-8')
    msg.attach(text_plain)

   
# 设置附件,file_path是附件的路径,请按实际情况修改
   
file_path = "d:\\fail-report.html"
   
sendfile = MIMEApplication(open(file_path, 'rb').read())
    sendfile.add_header(
'Content-Disposition', 'attachment', filename='fail-report.html')
    msg.attach(sendfile)

   
try:
        smtpObj = smtplib.SMTP()
        smtpObj.connect(mail_host)
        smtpObj.login(mail_user, mail_pass)
        smtpObj.sendmail(sender, receivers, msg.as_string())
       
print ("邮件发送成功")
   
except smtplib.SMTPException:
       
print ("邮件发送失败")


该文章对你有帮助吗,求分享转发: 分享到QQ空间 分享给QQ好友

 

 

粤ICP备19116230号
友情链接: 码农藏书阁 天天链